#!/bin/bash

version=1.2
echo "This script version is:$version"
if [ "$(id -u)" != "0" ]; then
   echo "This script must be run as root!" 1>&2
   exit 1
fi

FAT_MOUNT=/media/boot

mkdir $FAT_MOUNT 2>/dev/null
umount /dev/mmcblk0p1 2>/dev/null
mount /dev/mmcblk0p1 $FAT_MOUNT

if [ $? -ne 0 ]
then
  echo "Mounting /dev/mmcblk0p1 failed - already mounted?" 1>&2
  exit 1
fi

board=$(cat /proc/device-tree/model) >&2
if [[ $board =~ "ZED" ]]; then
        tree="zedboard.dts"
        echo "Current board is ZedBoard"
elif [[ $board =~ "ZC706" ]]; then
        tree="avc.dts"
        echo "Current board is ZC706"
else
        echo "Device tree don't have describe as ZedBoard or ZC706"
        exit 1
fi

# Try to restore current BOOT.BIN and devicetree.dtb
CURRENT_CONFIG="$FAT_MOUNT/dts"
echo "CURRENT BOARD CONFIG: $CURRENT_CONFIG"

if [ "$CURRENT_CONFIG" != "" ]
then
	for i in $(find $CURRENT_CONFIG -type d 2>/dev/null)
	do
		cd $i
		if [ -f $tree.dts ];then
			echo "Start rebuild devicetree..."
			dtc -O dtb -o devicetree.dtb $tree.dts 2>/dev/null
			break
		fi
	done
  echo "Updating $CURRENT_CONFIG/devicetree.dtb -> $FAT_MOUNT/devicetree.dtb"
  cp $CURRENT_CONFIG/devicetree.dtb $FAT_MOUNT/devicetree.dtb
fi

cd ~
sync
umount $FAT_MOUNT
echo "DONE"
